using MediatR;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;
using System.Linq;
using WMS.API.Application.Command.SystemUser;
using WMS.Domain.Entities.SystemUser;
using WMS.ErrorCode;
using WMS.Interfactructure.Interfaces;


namespace WMS.API.Application.CommandHandlers.SystemUser
{
    /// <summary>
    /// 导出财务明细命令处理器
    /// </summary>
    public class ExportFinancialdetailsQueryHandler : IRequestHandler<ExportFinancialdetailsQuery, APIResult<byte[]>>
    {
        private readonly IBaseRepository<Financialdetails> _baseRepository;

        public ExportFinancialdetailsQueryHandler(IBaseRepository<Financialdetails> baseRepository)
        {
            _baseRepository = baseRepository;
        }

        public async Task<APIResult<byte[]>> Handle(ExportFinancialdetailsQuery request, CancellationToken cancellationToken)
        {
            APIResult<byte[]> res = new APIResult<byte[]>("导出财务明细成功")
            {
                Code = ResultCode.Success
            };

            try
            {
                IQueryable<Financialdetails> query = _baseRepository.GetAll();

                // 根据搜索字段和搜索值进行过滤
                if (!string.IsNullOrEmpty(request.SearchField) && !string.IsNullOrEmpty(request.SearchValue))
                {
                    switch (request.SearchField.ToLower())
                    {
                        case "usercode":
                            query = query.Where(f => f.UserCode.Contains(request.SearchValue));
                            break;
                        case "typeof":
                            query = query.Where(f => f.Typeof.Contains(request.SearchValue));
                            break;
                        case "depositmethod":
                            query = query.Where(f => f.DepositMethod.Contains(request.SearchValue));
                            break;
                        case "trackingnumber":
                            query = query.Where(f => f.TrackingNumber.Contains(request.SearchValue));
                            break;
                        case "warehousename":
                            query = query.Where(f => f.WarehouseName.Contains(request.SearchValue));
                            break;
                        case "tariffstandard":
                            query = query.Where(f => f.TariffStandard.Contains(request.SearchValue));
                            break;
                        case "feedetailed":
                            query = query.Where(f => f.FeeDetailed.Contains(request.SearchValue));
                            break;
                        case "itemdetails":
                            query = query.Where(f => f.ItemDetails.Contains(request.SearchValue));
                            break;
                        default:
                            break;
                    }
                }

                // 根据时间范围进行过滤
                if (request.StartTime.HasValue)
                {
                    query = query.Where(f => f.StartTime >= request.StartTime.Value);
                }
                if (request.EndTime.HasValue)
                {
                    query = query.Where(f => f.StartTime <= request.EndTime.Value);
                }

                List<Financialdetails> data = query.ToList();

                //使用 NPOI 生成 Excel 文件
                XSSFWorkbook workbook = new XSSFWorkbook();
                XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("财务明细");

                // 创建表头
                XSSFRow headerRow = (XSSFRow)sheet.CreateRow(0);
                headerRow.CreateCell(0).SetCellValue("用户编码");
                headerRow.CreateCell(1).SetCellValue("类型");
                headerRow.CreateCell(2).SetCellValue("支付方式");
                headerRow.CreateCell(3).SetCellValue("充值金额（元）");
                headerRow.CreateCell(4).SetCellValue("开始时间");
                headerRow.CreateCell(5).SetCellValue("结束时间");
                headerRow.CreateCell(6).SetCellValue("操作备注");
                headerRow.CreateCell(7).SetCellValue("运单号");
                headerRow.CreateCell(8).SetCellValue("仓库名称");
                headerRow.CreateCell(9).SetCellValue("资费标准");
                headerRow.CreateCell(10).SetCellValue("费用详情");
                headerRow.CreateCell(11).SetCellValue("物品详情");

                // 填充数据
                int rowNum = 1;
                foreach (var item in data)
                {
                    IRow row = sheet.CreateRow(rowNum++);
                    row.CreateCell(0).SetCellValue(item.UserCode);
                    row.CreateCell(1).SetCellValue(item.Typeof);
                    row.CreateCell(2).SetCellValue(item.DepositMethod);
                    row.CreateCell(3).SetCellValue(item.Maney);
                    row.CreateCell(4).SetCellValue(item.StartTime.ToString("yyyy-MM-dd HH:mm:ss"));
                    row.CreateCell(5).SetCellValue(item.EndTime?.ToString("yyyy-MM-dd HH:mm:ss"));
                    row.CreateCell(6).SetCellValue(item.Remark);
                    row.CreateCell(7).SetCellValue(item.TrackingNumber);
                    row.CreateCell(8).SetCellValue(item.WarehouseName);
                    row.CreateCell(9).SetCellValue(item.TariffStandard);
                    row.CreateCell(10).SetCellValue(item.FeeDetailed);
                    row.CreateCell(11).SetCellValue(item.ItemDetails);
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    res.Data = ms.ToArray();
                }
            }
            catch (Exception ex)
            {
                res.Message = "导出财务明细失败: " + ex.Message;
                res.Code = ResultCode.Failed;
            }

            return res;
        }
    }
} 